package cn.jobstart.interceptor;


import cn.jobstart.common.NumberUtil;
import cn.jobstart.common.redis.RedisUtil;
import cn.jobstart.exception.ExceptionMessage;
import cn.jobstart.web.common.SkJsonResult;
import cn.jobstart.web.common.token.AdminToken;
import cn.jobstart.web.common.token.JwtsUtil;
import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author sunke
 * @Date 2018/8/1 01:55
 * @description
 */
@Component(value = "loginInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    private JwtsUtil jwtsUtil;


    @Autowired
    private RedisUtil redisUtil;


    public static void noLogin(HttpServletResponse response) {
       // response.addHeader("Access-Control-Allow-Origin", "*");
     //   response.addHeader("Access-Control-Expose-Headers", "Authorization,X-Requested-With,Content-Type,jsonType,json-type," + JwtsUtil.ADMIN_HEADER_KEY + ",Adminauthorization");


        String msg = "用户未登录或被其它人踢出";

        try {
            int code = NumberUtil.parseInt(ExceptionMessage.EXIST_CLIENT_NOT_LOGIN.split("@@")[1]);

            response.setContentType("application/json;charset = UTF-8");

            SkJsonResult skJsonResult = new SkJsonResult().setFail(msg);
            skJsonResult.setErrorCode(code);

            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(skJsonResult));
            writer.flush();
            writer.close();


        } catch (Exception e) {

        }

    }

    public JwtsUtil getJwtsUtil() {
        return jwtsUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {


        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(200);
            //  chain.doFilter(request, response);
            return true;
        }


        String header = request.getHeader(JwtsUtil.ADMIN_HEADER_KEY);

        if (header == null || !header.startsWith(JwtsUtil.ADMIN_HEADER_KEY_PREFIX)) {


            noLogin(response);
            return false;

        }


        try {
            AdminToken adminToken =
                    jwtsUtil.parseAdminToken(header);

            if (adminToken == null) {
                noLogin(response);
                return false;
            }


            // int singLoginFlag = NumberUtil.parseInt(staffToken.getSingleLoginFlag(), StaffSingleLoginFlagEnum.Y.getType().intValue());

            //找一下这个用户对应的是那一个rediskey 看看是不是最新的，不是最新的，说明无效
            //  String redisKey = StringUtil.toString(redisUtil.get("point" + adminToken.getAdminId()));

       /*     //说明要单点登录
            if (singLoginFlag == StaffSingleLoginFlagEnum.Y.getType().intValue()) {

                if (!staffToken.getRedisKey().equalsIgnoreCase(redisKey)) {
                    noLogin(response);
                    return false;
                }
            }*/


            //说明超过2小时
            if (System.currentTimeMillis() - adminToken.getCreateTime() > 2 * 3600 * 1000) {
                noLogin(response);
                return false;
            }


            //去刷新
            if (jwtsUtil.isRefreshToken(adminToken)) {
                response.setHeader(JwtsUtil.ADMIN_HEADER_KEY, jwtsUtil.createAdminToken(adminToken, System.currentTimeMillis()));
            } else {
                response.setHeader(JwtsUtil.ADMIN_HEADER_KEY, header);
            }


            return true;

        } catch (Exception e) {

        }


        noLogin(response);
        return false;


    }

}
